package cn.ljy.authority.web.controller.backstage.system.file;


import cn.ljy.authority.config.security.UserUtil;
import cn.ljy.authority.config.upload.FileUploadConfig;
import cn.ljy.authority.model.SysFileResource;
import cn.ljy.authority.model.common.AuthorityConstant;
import cn.ljy.authority.model.query.SysFileResourceQuery;
import cn.ljy.authority.service.SysFileResourceService;
import cn.ljy.common.annotation.LimitRequest;
import cn.ljy.common.exception.model.MyServiceException;
import cn.ljy.common.model.result.ResponseData;
import cn.ljy.common.utils.file.MyFileModel;
import cn.ljy.common.utils.file.MyFileOperator;
import cn.ljy.common.utils.file.MyFileUpload;
import cn.ljy.common.utils.page.Pagination;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;

@Api(tags = "后台上传文件通用管理模块")
@RestController
@RequestMapping(value = "/backstage/system/fileResource")
public class SysFileResourceController {
    @Autowired
    private SysFileResourceService service;
    @Autowired
    private FileUploadConfig fileUploadConfig;

    @ApiOperation(value = "分页查询文件资源列表")
    @LimitRequest
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页最大记录数", defaultValue = "20")
    })
    @PreAuthorize("hasAuthority('sys:fileResource:query')")
    @GetMapping
    protected ResponseData query(Integer page, Integer pageSize, SysFileResourceQuery query) {
        Pagination pagination = service.findAll(page,pageSize,query);
        return ResponseData.success(pagination);
    }

    @ApiOperation(value = "读取资源")
    @LimitRequest
    @PreAuthorize("hasAuthority('sys:fileResource:query')")
    @GetMapping("/{id}")
    protected ResponseData get(@PathVariable String id) {
        SysFileResource sysFileResource=service.get((Serializable)id);
        if(sysFileResource!=null){
            return ResponseData.success(sysFileResource);
        }else{
            return ResponseData.error("找不到指定记录");
        }
    }

    @ApiOperation(value = "批量删除资源")
    @LimitRequest
    @ApiImplicitParam(name = "ids", value = "要删除的id集合", required = true,paramType = "query",example ="[11,12,13]")
    @PreAuthorize("hasAuthority('sys:fileResource:del')")
    @DeleteMapping
    protected ResponseData deletes(@NotEmpty(message = "请选择要移除的记录") String[] ids) {
        service.delete((Serializable[])ids);
        return ResponseData.success(null);
    }

    @ApiOperation(value = "文件添加")
    @PreAuthorize("hasAuthority('sys:fileResource:upload')")
    @PostMapping
    protected ResponseData add(@NotNull(message="请选择上传文件") MultipartFile file,SysFileResource fileResource) {
        ResponseData responseData;
        //1.获取要保存的物理路径。c:/ljy-mes-management/upload/resource
        String savePath=fileUploadConfig.getResourceUploadSavePath();
        //2.获取要回显的路径。/resource/upload/resource/
        String baseUploadUrl=fileUploadConfig.getResourceUploadUrl();
        //3.执行文件上传
        MyFileModel myFileModel = MyFileUpload.uploadMultipartFile(file, fileResource.getResourceType(), savePath, baseUploadUrl, true, AuthorityConstant.ALLOW_UPLOAD_RESOURCE_SIZE);
        //4.保存信息到系统中
        fileResource.setAuthor(UserUtil.getLoginUser());
        fileResource.setFileUrl(myFileModel.getFileRelativePath());
        fileResource.setOriginFileName(myFileModel.getFileNameOfOrigin());
        fileResource.setResourceSize(myFileModel.getFileSize());
        try {
            //存入数据库
            service.save(fileResource);
            responseData=ResponseData.success(null);
        } catch (Exception e) {
            //6（可选）：如果保存出异常，则删除上传的文件
            MyFileOperator.deleteFile(myFileModel.getFilePath());
            //返回异常信息
            throw new MyServiceException(e.getMessage());
        }
        return responseData;
    }

    @ApiOperation(value = "文件编辑")
    @PreAuthorize("hasAuthority('sys:fileResource:edit')")
    @PutMapping
    protected ResponseData edit(@RequestBody SysFileResource fileResource) {
        fileResource.setLastAuthor(UserUtil.getLoginUser());
        service.update(fileResource);
        return ResponseData.success(null);
    }

    @ApiOperation(value = "文件上传",notes = "可以用于日志模块、产品模块等文件上传")
    @PreAuthorize("hasAuthority('sys:fileResource:upload')")
    @PostMapping("/upload")
    protected ResponseData upload(@NotNull(message="请选择上传文件") MultipartFile file,String dirName) {
        ResponseData responseData;
        //1.获取要保存的物理路径。c:/ljy-mes-management/upload/resource
        String savePath=fileUploadConfig.getResourceUploadSavePath();
        //2.获取要回显的路径。/resource/upload/resource/
        String baseUploadUrl=fileUploadConfig.getResourceUploadUrl();
        //3.执行文件上传
        MyFileModel myFileModel = MyFileUpload.uploadMultipartFile(file, dirName, savePath, baseUploadUrl, true,AuthorityConstant.ALLOW_UPLOAD_RESOURCE_SIZE);
        //4.保存信息到系统中
        SysFileResource fileResource=new SysFileResource();
        fileResource.setAuthor(UserUtil.getLoginUser());
        fileResource.setFileUrl(myFileModel.getFileRelativePath());
//        fileResource.setTitle(myFileModel.getFileName());
        fileResource.setTitle(myFileModel.getFileNameOfOrigin());
        fileResource.setOriginFileName(myFileModel.getFileNameOfOrigin());
        fileResource.setResourceSize(myFileModel.getFileSize());
        fileResource.setResourceType(myFileModel.getFileType());
        try {
            //存入数据库
            service.save(fileResource);
            responseData=ResponseData.success(myFileModel);
        } catch (Exception e) {
            //6（可选）：如果保存出异常，则删除上传的文件
            MyFileOperator.deleteFile(myFileModel.getFilePath());
            //返回异常信息
            responseData=ResponseData.error(e.getMessage());
        }
        return responseData;
    }

    /**
     * 导出文件
     */
    @ApiOperation(value = "文件下载")
    @GetMapping("/download/{id}")
    public void download(HttpServletResponse response,@PathVariable("id") String id){
        //从数据库读取资源路径
        SysFileResource fileResource = service.get(id);
        //拼接出文件所在的物理路径
        String filePath=fileUploadConfig.getResourceUploadSavePath()+fileResource.getFileUrl();
        MyFileOperator.downloadByHutool(fileResource.getTitle(),filePath,response);
    }



    //=========================扩展部分=============================================//
}
